//
//  UIViewController+DismissKeyboard.swift
// @project：JWHelperKit
// @author：linjw(10126121@qq.com)
// @time: 2022/12/20
// Copyright © 2018年 Linjw. All rights reserved.
//

import UIKit

public extension JWNamespaceWrapper where T: UIViewController {
    
    /// 设置点击背景隐藏键盘
    func setupForDismissKeyboard() { jwWrappedValue.setupForDismissKeyboard() }
    
}

fileprivate extension UIViewController {
    
    /// 设置隐藏键盘
    fileprivate func setupForDismissKeyboard() {
        
        let nc = NotificationCenter.default
        let singleTapGR = UITapGestureRecognizer(target: self, action: #selector(tapAnywhereToDismissKeyboard(_:)))
        
        let mainQuene = OperationQueue.main
        nc.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: mainQuene, using: { [weak self] _ in
            self?.view.addGestureRecognizer(singleTapGR)
        })
        nc.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: mainQuene, using: { [weak self] _ in
            self?.view.removeGestureRecognizer(singleTapGR)
        })
    }
    
    @objc fileprivate func tapAnywhereToDismissKeyboard(_ gest: UIGestureRecognizer) {
        self.view.endEditing(true)
    }
    
}
